<template>
  <div class="card content-box-c">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="first">
        <basic-info-form ref="basicInfoRef" v-if="isRouter" :model="info" />
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="second">
        <column-info ref="tableInfoRef" v-if="isRouter" :dict-options="dictOptions" :table-data="columns" />
      </el-tab-pane>
      <el-tab-pane label="生成信息" name="third">
        <gen-info-form ref="genInfoRef" v-if="isRouter" :model="info" :tables="tables" :menus="menus" />
      </el-tab-pane>
    </el-tabs>
    <div v-show="isRouter" style="margin-top: 20px; margin-left: -100px; text-align: center">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="useProTableDetail">
import { ElMessage } from 'element-plus'
import BasicInfoForm from './components/basicInfoForm.vue'
import GenInfoForm from './components/genInfoForm.vue'
import ColumnInfo from './components/columnInfo.vue'
import { getTableApi, updateGenTableApi } from '@/api/modules/tool/gen'
import { optionSelectApi } from '@/api/modules/system/dict'
import { listMenuApi } from '@/api/modules/system/menu'
import { handleTree } from '@/utils/common'
interface MenuOptionsType {
  menuId: number | string
  menuName: string
  children?: MenuOptionsType[]
}
const basicInfoRef = ref<InstanceType<typeof BasicInfoForm> | null>(null)
const genInfoRef = ref<InstanceType<typeof GenInfoForm> | null>(null)
const tableInfoRef = ref<InstanceType<typeof ColumnInfo> | null>(null)
const activeName = ref('first')
const route = useRoute()
const router = useRouter()
const isRouter = ref<boolean>(false)
// 表信息
const tables = ref<any>([])
// 表列信息
const columns = ref<any>([])
// 字典信息
const dictOptions = ref<any>([])
// 菜单信息
const menus = ref<any>([])
// 表详细信息
const info = ref<any>({})
onMounted(() => {
  const tableId = route.params && (route.params.tableId as string)
  isRouter.value = false
  if (tableId) {
    initTabsData(tableId)
  }
})
const initTabsData = async (tableId: string) => {
  if (!tableId) {
    console.log('参数异常')
    return
  }
  // 获取表详细信息
  await getTableApi(tableId).then((response: any) => {
    if (response.code === 200) {
      const data = response.data
      columns.value = data.rows
      info.value = data.info
      tables.value = data.tables
    }
  })
  /** 查询字典下拉列表 */
  await optionSelectApi().then((response: any) => {
    if (response.code === 200) {
      dictOptions.value = response.data
    }
  })
  /** 查询菜单下拉列表 */
  const response = await listMenuApi()
  if (response.code === 200) {
    response.data.forEach(m => (m.menuId = String(m.menuId)))
    menus.value = handleTree<MenuOptionsType>(response.data, 'menuId')
  }
  isRouter.value = true
}
// 定义 emit 事件
const emit = defineEmits<{
  submitForm: []
}>()
const formAllValidate = (form: any) => {
  return new Promise(resolve => {
    if (form) {
      form.validate((res: any) => {
        resolve(res)
      })
    } else {
      resolve(true)
    }
  })
}
const submitForm = () => {
  const basicEl = basicInfoRef.value?.formRef?.proFormRef
  const refsEl = genInfoRef.value?.formRef?.proFormRef
  const refsEl2 = genInfoRef.value?.formRef2?.proFormRef
  const genTable2 = Object.assign({}, genInfoRef.value?.formRef2?.formModel)
  Promise.all([basicEl, refsEl, refsEl2].map(formAllValidate)).then((res: any) => {
    const validate = res.every((item: any) => !!item)
    if (validate) {
      const genTable = Object.assign({}, info.value)
      genTable.subTableFkName = genTable2.subTableFkName
      genTable.subTableName = genTable2.subTableName
      genTable.columns = columns.value
      genTable.params = {
        treeCode: genTable2.treeCode,
        treeName: genTable2.treeName,
        treeParentCode: genTable2.treeParentCode,
        parentMenuId: genTable.parentMenuId
      }
      updateGenTableApi(genTable).then((response: any) => {
        if (response.code === 200) {
          ElMessage({
            type: 'success',
            message: `操作成功!`
          })
          back()
        }
      })
    } else {
      ElMessage({
        type: 'error',
        message: `校验不通过，请检查配置信息!`
      })
    }
  })
  emit('submitForm')
}
const back = () => {
  router.push({ path: '/tool/gen' })
}
</script>
